<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="主机名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入主机名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="主机编码" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入主机编码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="主机地址" prop="address">
        <el-input
          v-model="queryParams.address"
          placeholder="请输入主机地址"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['os:host:add']"
        >新增</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <!-- 卡片式列表展示 -->
    <el-row :gutter="20">
      <el-col v-for="(host, index) in hostList" :key="index" :span="6">
        <el-card class="host-card">
        <div class="host-card-content">
        <div class="host-title">
          {{ host.name }}
        </div>
        <div class="host-divider"></div>
            <p class="host-label">主机类型：<dict-tag class="dict-tag" :options="host_type" :value="host.types" /></p>
            <p class="host-label">系统类型：{{ host.osType }}</p>
            <p class="host-label">系统架构：{{ host.archType }}</p>
            <p class="host-label">主机编码：{{ host.code }}</p>
            <p class="host-label">主机地址：{{ host.address }}</p>
            <p class="host-label">主机状态：<dict-tag class="dict-tag" :options="service_status" :value="host.status"/></p>
            <p class="host-label">备注：{{ host.remark }}</p>
            <div class="host-actions">
              <el-button link type="primary" icon="link" @click="linkHost(host)" v-hasPermi="['os:host:edit']">远程</el-button>
              <el-button link type="primary" :icon ="host.status == 0? 'Lock' : 'Unlock'" @click="handleUpdateStatus(host)" v-hasPermi="['os:host:edit']"> {{ host.status ==0 ? '停用' : '启用' }}</el-button>
              <el-button link type="primary" icon="Edit" @click="handleUpdate(host)" v-hasPermi="['os:host:edit']">修改</el-button>
              <el-button link type="primary" icon="Delete" @click="handleDelete(host)" v-hasPermi="['os:host:remove']">删除</el-button>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 新增/编辑主机的弹框（核心新增部分） -->
    <HostEditDialog
        v-model:visible="dialogVisible"
        :is-edit="isEdit"
        :init-form="initForm"
        @refresh="handleRefresh" 
    />
  </div>
</template>

<script setup name="Host">
import HostEditDialog from '@/views/os/host/HostEditDialog.vue'; 
import { listHost, getHost, delHost, addHost, updateHost, getHostSsh, getHostSpec } from "@/api/os/host"
const dialogVisible = ref(false); // 控制弹框显示/隐藏
const isEdit = ref(false);       // 标记"新增"或"编辑"
const initForm = ref({});       // 编辑时，从接口拉取的初始化数据
const { proxy } = getCurrentInstance()
const { os_type,arch_type,host_type,service_status } = proxy.useDict("os_type","arch_type","host_type","service_status")
const hostList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    types: null,
    osType: null,
    archType: null,
    name: null,
    code: null,
    address: null,
    status: null,
  },
  rules: {
  }
})
const { queryParams, form, rules } = toRefs(data)

/** 查询主机列表 */
function getList() {
  loading.value = true
  listHost(queryParams.value).then(response => {
    hostList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 添加刷新方法
function handleRefresh(needClose = true) {
  getList();
  if (needClose) {
    dialogVisible.value = false;
  }
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    types: null,
    osType: null,
    archType: null,
    name: null,
    code: null,
    address: null,
    status: null
  }
  proxy.resetForm("hostRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据（这里可以根据实际需求调整，例如点击卡片进行选择等）
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  isEdit.value = false;
  initForm.value = {}; // 清空初始化数据
  dialogVisible.value = true
}

/** 修改按钮操作 */
async function handleUpdate(row) {
  reset();
  const _id = row.id;
  
  try {
    // 只获取主机基本信息，其他标签页数据在点击时再加载
    const hostResponse = await getHost(_id);
    
    initForm.value = {
      ...hostResponse.data
    };
    
    isEdit.value = true;
    dialogVisible.value = true;
  } catch (error) {
    console.error('获取主机详情失败', error);
    proxy.$modal.msgError("获取主机详情失败");
  }
}

/** 启用/停用按钮操作 */
function handleUpdateStatus(host) {
  const newStatus = host.status == 0 ? 1 : 0;
  const actionText = newStatus == 0 ? '启用' : '停用';
  proxy.$modal.confirm(`确定要${actionText}主机“${host.name}”吗？`).then(() => {
    updateHost({ id: host.id, status: newStatus }).then(() => {
      proxy.$modal.msgSuccess(`${actionText}成功`);
      getList();
    });
  }).catch(() => {});
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["hostRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateHost(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addHost(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除主机编号为"' + _ids + '"的数据项？').then(function() {
    return delHost(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

getList()
</script>

<style scoped>
.host-card {
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  border-radius: 5px;
  transition: box-shadow 0.3s ease;
}

.host-card:hover {
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

.host-card-content {
  padding: 16px;
}

.host-label {
  margin-bottom: 8px;
  font-weight: 500;
}

.host-actions {
  margin-top: 16px;
}
::v-deep .dict-tag {
  display: inline-block;
  vertical-align: middle;
}
.host-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 10px;
  text-align: left;
  color: #333;
}
.host-divider {
  border-bottom: 1px dashed #bbb;
  margin-bottom: 12px;
}
</style>